<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 选项卡的渲染
      最外层是个el-tabs
      里边每一个选项卡是通过el-tab-pane来渲染的
      el-tabl-pane选项卡的文本 是通过label属性来设置
      el-tabs的v-model绑定的值 和 el-tab-pane中name属性绑定在一块
      @tab-click 事件 是点击每个选项卡的时候触发
       -->
      <el-card v-loading="isLoading">
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="addRoleFn"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table :data="roleList">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="showAssignDialogFn(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- current-page 表示的当前是哪一页 -->
            <!-- page-sizes 动态设置页容量的下拉列表 -->
            <!-- page-size 表示的是当前的页容量 -->
            <!-- layout 表示的分页的展示样式 -->
            <!-- total 表示的 一共有多少条 -->
            <!-- @current-change 表示的点击页码的时候执行的事件-->
            <!-- @size-change 表示的动态设置页容量的时候执行的事件 -->
            <div
              style="margin-top: 10px; display: flex; justify-content: flex-end"
            >
              <el-pagination
                :current-page="page"
                :page-sizes="[2, 3, 4, 5]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="showTitle" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmAddRole">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        :close-on-click-modal="false"
        @close="closeAssignDialog"
        @open="dialogOpenFn"
      >
        <el-tree
          ref="tree"
          v-loading="isAssignLoading"
          :data="settingList"
          :props="{label:'name'}"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="assignPermAPIFn">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleListApi, delRoleApi, addRoleApi, getRoleDetailApi, editRoleApi, getCompanyInfoApi, assignPermAPI } from '@/api/setting'
import { mapGetters } from 'vuex'
import { transListToTreeData } from '@/utils/index'
import { getPermissionListAPI } from '@/api/permission'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1,
      pagesize: 10,
      roleList: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      showAssignDialog: false,
      roleId: '',
      isAssignLoading: false,
      settingList: [],
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      }
    }
  },
  computed: {
    ...mapGetters(['companyId']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 分配权限-角色
    async assignPermAPIFn() {
      // tree组件提供的key方法获取permIds
      const permIds = this.$refs.tree.getCheckedKeys()
      // 调用接口传对应的参数
      await assignPermAPI({ id: this.roleId, permIds })
      this.$message.success('分配成功')
      this.closeAssignDialog()
    },
    async dialogOpenFn() {
      this.isAssignLoading = true
      await this.getPermissionListAPIFn()
      await this.getRoleDetailApiFn()
      this.isAssignLoading = false
    },
    // 获取数据转换为树状结构
    async getPermissionListAPIFn() {
      const { data } = await getPermissionListAPI()
      this.settingList = transListToTreeData(data, '0')
    },
    // 数据回显
    async getRoleDetailApiFn() {
      const { data: { permIds }} = await getRoleDetailApi(this.roleId)
      // 使用tree组件提供的setCheckedKeys方法通过 key 来获取或设置
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 当点击分配权限时把对应节点的id传入roleId
    showAssignDialogFn(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async getCompanyInfo() {
      const { data } = await getCompanyInfoApi(this.companyId)
      this.companyForm = data
    },
    async editRole(id) {
      this.showDialog = true
      const { data } = await getRoleDetailApi(id)
      this.form = data
    },
    confirmAddRole() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          await editRoleApi(this.form)
          this.$message.success('恭喜！修改成功')
        } else {
          await addRoleApi(this.form)
          this.$message.success('恭喜！添加成功')
        }
        // this.page = Math.ceil((this.total + 1) / this.pagesize)
        this.getRoleList()
        this.closeDialog()
      })
    },
    addRoleFn() {
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      // 清空的是 绑定了prop的表单域的状态和数据
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    delRole(id) {
      this.$confirm('亲！您确定要删除吗？', '温馨提示').then(async() => {
        await delRoleApi(id)
        this.$message.success('删除成功')
        if (this.roleList.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRoleList()
      }).catch(() => {})
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    async getRoleList() {
      this.isLoading = true
      const { data } = await getRoleListApi(this.page, this.pagesize)
      this.roleList = data.rows
      this.total = data.total
      this.isLoading = false
    },
    /**
     * 点击页码
     */
    handleCurrentChange(val) {
      // console.log(val)
      this.page = val
      this.getRoleList()
    },
    /**
     * 修改页容量
     */
    handleSizeChange(val) {
      // console.log(val)
      this.pagesize = val
      this.getRoleList()
    }
  }
}
</script>

<style>
</style>
